package com.yz.aiks.multimodules.configuration;

import com.yz.aiks.multimodules.JedisUtils;
import com.yz.aiks.multimodules.config.JedisConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;

/**
 * @author <a href="mailto:aiks_yuan@163.com">yuanz</a>
 * @date 2022-02-24 10:34
 * @since 1.0.0
 **/
@Configuration
@EnableConfigurationProperties(JedisConfig.class)
public class JedisConfiguration {
    
    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig(final JedisConfig jedisConfig) {
        GenericObjectPoolConfig<JedisPool> genericObjectPoolConfig = new GenericObjectPoolConfig<>();
        genericObjectPoolConfig.setMaxIdle(jedisConfig.getPool().getMaxIdle());
        genericObjectPoolConfig.setMaxTotal(jedisConfig.getPool().getMaxTotal());
        genericObjectPoolConfig.setMaxWaitMillis(jedisConfig.getPool().getMaxWaitMillis());
        genericObjectPoolConfig.setMinIdle(jedisConfig.getPool().getMinIdle());
        genericObjectPoolConfig.setTestWhileIdle(jedisConfig.getPool().isTestWhileIdle());
        genericObjectPoolConfig.setTestOnBorrow(jedisConfig.getPool().isTestOnBorrow());
        genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(jedisConfig.getPool().getTimeBetweenEvictionRunsMillis());
        return genericObjectPoolConfig;
    }
    
    @Bean("jedisPool")
    public JedisPool jedisPool(final @Qualifier("genericObjectPoolConfig") GenericObjectPoolConfig genericObjectPoolConfig,
                               final JedisConfig jedisConfig) {
        String password = null;
        if (StringUtils.isNotBlank(jedisConfig.getPassword())) {
            password = jedisConfig.getPassword();
        }
        JedisPool jedisPool = new JedisPool(genericObjectPoolConfig, jedisConfig.getHostname(), jedisConfig.getPort()
            , jedisConfig.getTimeout(), password);
        return jedisPool;
    }
    
    @Bean("jedisUtils")
    @ConditionalOnProperty(name = "aiks.redis.cluster", havingValue = "true", matchIfMissing = true)
    public JedisUtils jedisUtils(final @Qualifier("jedisPool") JedisPool jedisPool) {
        JedisUtils jedisUtils = new JedisUtils();
        jedisUtils.setJedisPool(jedisPool);
        return jedisUtils;
    }
    
}
